package UI;

import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingConstants;

import threads.BaseRunnableBCBS;
import Logic.SQLReader;
import UI.BaseModels.BCBSPanel;
import javax.swing.ImageIcon;

public class LoginPanel extends BCBSPanel {

	private static final long serialVersionUID = -4309001492841610373L;
	private JTextField emailLoginField;
	private JPasswordField passwordLoginField;
	private JButton confirmButton;

	public LoginPanel() {

		emailLoginField = new JTextField();
		emailLoginField.setHorizontalAlignment(SwingConstants.CENTER);
		emailLoginField.setBounds(67, 270, 177, 27);
		this.add(emailLoginField);
		emailLoginField.setColumns(10);

		JLabel lblEmail = new JLabel("CBS E-mail:");
		lblEmail.setVerticalAlignment(SwingConstants.TOP);
		lblEmail.setFont(new Font("Tahoma", Font.BOLD, 15));
		lblEmail.setHorizontalAlignment(SwingConstants.CENTER);
		lblEmail.setBounds(94, 250, 123, 19);
		this.add(lblEmail);

		JLabel lblPassword = new JLabel("Password:");
		lblPassword.setFont(new Font("Tahoma", Font.BOLD, 15));
		lblPassword.setHorizontalAlignment(SwingConstants.CENTER);
		lblPassword.setBounds(117, 310, 78, 19);
		this.add(lblPassword);

		confirmButton = new JButton("Login");
		confirmButton.addActionListener(new Login());
		confirmButton.setFont(new Font("Tahoma", Font.BOLD, 12));
		confirmButton.setBounds(100, 370, 111, 27);
		this.add(confirmButton);

		passwordLoginField = new JPasswordField();
		passwordLoginField.setHorizontalAlignment(SwingConstants.CENTER);
		passwordLoginField.setBounds(67, 330, 177, 27);
		passwordLoginField.addActionListener(new Login());
		this.add(passwordLoginField);

		feedbackLabel.setLocation(3, 292);

		JButton btnExit = new JButton("Exit");
		btnExit.setBounds(117, 410, 78, 23);
		btnExit.addActionListener(new Exit());
		this.add(btnExit);

		JLabel lblNewLabel = new JLabel("");
		lblNewLabel.setIcon(new ImageIcon(LoginPanel.class
				.getResource("/Programmeringsbilleder/LoginScreen(edit).jpg")));
		lblNewLabel.setBounds(-18, -22, 370, 493);
		add(lblNewLabel);

	}

	/**
	 * Clears feedback-label, text fields and enables the Login-button.
	 */
	@Override
	public void clearFields() {
		feedbackLabel.setText("");
		passwordLoginField.setText("");
		emailLoginField.setText("");
		enableConfirmButton();
	}

	/**
	 * Enables the Confirm-button.
	 */
	public void enableConfirmButton() {
		passwordLoginField.setEnabled(true);
		confirmButton.setEnabled(true);
	}

	/**
	 * Enables the Confirm-button.
	 */
	public void disableConfirmButton() {
		passwordLoginField.setEnabled(false);
		confirmButton.setEnabled(false);
	}

	/**
	 * Creates a new Runnable of the type LoginRunnable, sets it to the current
	 * runnable for the panel, places it in its own thread and runs it.
	 * Additionally this method tells the previously initiated thread to stop
	 * whatever it's doing first.
	 */
	private void login() {
		runnable = new LoginRunnable();
		Thread t = new Thread(runnable);
		t.start();
	}

	private class Login implements ActionListener {

		public void actionPerformed(ActionEvent arg0) {
			login();

		}
	}

	private class Exit implements ActionListener {

		public void actionPerformed(ActionEvent arg0) {
			System.exit(0);
		}

	}

	/**
	 * See the run-method of this class for details.
	 * 
	 */
	private class LoginRunnable extends BaseRunnableBCBS {

		/**
		 * 
		 * Login function. Checks for content in both email field and password.
		 * Initiates SQLReader and authenticates user information. Obtain user
		 * information afterwards through method SQLReader.getAccount, and
		 * displays either admin or user menu according to user information.
		 * 
		 */
		@Override
		public void run() {
			SQLReader reader = new SQLReader();
			boolean fieldcheck = true;
			String email = emailLoginField.getText().trim();
			char[] password = passwordLoginField.getPassword();

			if (password.length == 0 && email.length() > 0) {
				feedback("Password cannot be blank!", false);

				fieldcheck = false;
			}
			if (email.isEmpty() && password.length > 0) {
				feedback("E-mail cannot be blank!", false);

				fieldcheck = false;
			}
			if (email.isEmpty() && password.length == 0) {
				feedback("Please input credentials!", false);

				fieldcheck = false;
			}
			if (fieldcheck) {
				boolean validated = false;
				boolean connected = false;
				boolean gotuser = false;
				disableConfirmButton();
				clearFeedback();
				if (!stop) {
					try {
						validated = reader.authenticate(email, password);
						connected = true;
					} catch (SQLException e) {
						if (!stop) {
							feedback("Connection error! Try again!", false);
							enableConfirmButton();
						}
					}
					if (validated && !stop) {
						try {
							UI.MainFrame.currentUser = reader.getAccount(reader
									.getUserID(email));
							gotuser = true;
						} catch (SQLException e) {
							if (!stop) {
								feedback("Connection error! Try again!", false);
								enableConfirmButton();
							}
						}
						if (gotuser && !stop) {
							clearFields();
							UI.MainFrame.main_menu
									.setHeader(UI.MainFrame.currentUser
											.getFirstname());
							UI.MainFrame.main_menu.currentBalance
									.setText(String
											.valueOf(UI.MainFrame.currentUser
													.getBalance()));
							UI.MainFrame.login_start.setVisible(false);
							if (!UI.MainFrame.currentUser.isAdmin()) {
								UI.MainFrame.currentPanel = UI.MainFrame.main_menu;
								UI.MainFrame.main_menu.setVisible(true);
								UI.MainFrame.main_menu.refreshInfo();
							} else {
								UI.MainFrame.currentPanel = UI.MainFrame.admin_panel;
								UI.MainFrame.admin_panel.setVisible(true);
								UI.MainFrame.admin_panel.getExchangeRate();
							}
						}

					} else if (connected && !stop) {

						feedback("Incorrect e-mail or password!", false);
						enableConfirmButton();

					}
				}
			}
		}
	}
}
